import React, { useEffect, useState } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import MonitorList from '@/pages/monitorList';
import TaskList from '@/pages/taskList';
import TaskGroup from '@/pages/taskGroup';
import TaskInfo from '@/pages/taskInfo';
import FormPage from '@/pages/formPage';
import TestPage from '@/pages/testPage';
import BugStore from '@/pages/bugStore';
import Keyword from '@/pages/keyword';
import CustomModule from '@/pages/customModule';
import ChangeSet from '@/pages/changeSet';
import ChangeDetail from '@/pages/dashboard/ScanRes/changeCheck/Detail';
import Dashboard from '@/pages/dashboard';
import VulDetail from '@/pages/dashboard/ScanRes/vul/info';
import Detail from '@/pages/dashboard/ScanRes/outlink/Detail';
import SecurityInfo from '@/pages/dashboard/securityInfo';
import Message from '@/pages/message';
import UserManage from '@/pages/userManage';
import UserEdit from '@/pages/userManage/userEdit';
import ApiPage from '@/pages/userManage/apiPage';
import AuthMethod from '@/pages/authMethod';
import ErrorLog from '@/pages/errorLog';
import RemoteHelp from '@/pages/remoteHelp';
import LogCenter from '@/pages/logCenter';
import AlertPage from '@/pages/alertPage';
import ProductInfo from '@/pages/system/productInfo';
import SysUpdate from '@/pages/system/sysUpdate';
import BackupRecovery from '@/pages/backupRecovery';
import DnsConfig from '@/pages/network/dnsConfig';
import SshConfig from '@/pages/network/sshConfig';
import NetworkConfig from '@/pages/network/networkConfig';
import RouterConfig from '@/pages/network/routerConfig';
import SnmpConfig from '@/pages/network/snmpConfig';
import HttpsConfig from '@/pages/network/httpsConfig';

import Role from '@/pages/roleManage';
import BusinessLoad from '@/pages/sysStatus/businessLoad';
import InterfaceFlow from '@/pages/sysStatus/interfaceFlow';
import SystemControl from '@/pages/sysStatus/systemControl';
import SystemLoad from '@/pages/sysStatus/systemLoad';
import SysTime from '@/pages/sysStatus/sysTime';
import Down from '@/pages/down';
import NotFound from '@/pages/NotFound';
import AuthRoute from '../components/AuthRoute';
import cookie from 'react-cookies';
import { useHistory } from 'react-router-dom';
import {
  getUserInfoDetail as getUserInfoDetailApi,
  getRoleList as getRoleListApi,
} from '../../API/index';
const allNavs = [
  {
    icon: 'monitor',
    title: '监测列表',
    link: '/monitor',
    subChildren: [
      '/form_page',
      '/securityInfo/',
      '/vul_detail/',
      '/outlink/Detail',
      '/change_detail/',
    ],
  },
  {
    icon: 'task',
    title: '任务管理',
    children: [
      {
        title: '任务队列',
        link: '/task_list',
      },
      {
        title: '任务组',
        link: '/task_group',
        subChildren: ['/task_info/', /form_page.*type=group/],
      },
    ],
  },
  {
    icon: 'alert',
    title: '告警中心',
    link: '/alert_Page',
  },
  {
    icon: 'down',
    title: '报告下载',
    link: '/down',
  },
  {
    icon: 'keyword',
    title: '策略管理',
    children: [
      {
        title: '敏感词',
        link: '/keyword',
      },
      {
        title: '漏洞模版',
        link: '/custom_module',
      },
      {
        title: '变更基准',
        link: '/change_set',
      },
    ],
  },
  {
    icon: 'user',
    title: '用户管理',
    children: [
      {
        title: '用户列表',
        link: '/user_manage',
      },
      {
        title: '账号设置',
        link: '/user_edit',
      },
      {
        title: 'API管理',
        link: '/api_page',
      },
      {
        title: '认证方式',
        link: '/auth_method',
      },
    ],
  },
  {
    icon: 'role',
    title: '角色管理',
    link: '/role_manage',
  },
  {
    icon: 'log',
    title: '日志中心',
    link: '/log_center',
  },
  {
    icon: 'backup',
    title: '备份恢复',
    link: '/backup_recovery',
  },
  {
    icon: 'bug',
    title: '漏洞库',
    link: '/bug_store',
  },
  {
    icon: 'network',
    title: '网络配置',
    children: [
      {
        title: '网口配置',
        link: '/network_config',
      },
      {
        title: '路由配置',
        link: '/router_config',
      },
      {
        title: 'DNS配置',
        link: '/dns_config',
      },
      {
        title: 'SNMP配置',
        link: '/snmp_config',
      },
      {
        title: 'SSH配置',
        link: '/ssh_config',
      },
      // {
      //   title: 'HTTPS配置',
      //   link: '/https_config',
      // },
    ],
  },
  {
    icon: 'update',
    title: '升级服务',
    link: '/system_update',
  },
  {
    icon: 'product',
    title: '系统信息',
    link: '/product_info',
  },
  {
    icon: 'systemStatus',
    title: '系统状态',
    children: [
      {
        title: '系统负载',
        link: '/system_load',
      },
      {
        title: '业务负载',
        link: '/business_load',
      },
      {
        title: '系统时间',
        link: '/system_time',
      },
      {
        title: '系统控制',
        link: '/system_control',
      },
      {
        title: '接口流量',
        link: '/interface_flow',
      },
    ],
  },
  {
    icon: 'remote',
    title: '问题排查',
    children: [
      {
        title: '远程协助',
        link: '/remote_help',
      },
    ],
  },
];
const NavDataAdmin = [
  {
    path: '/down',
    component: Down,
  },
  {
    path: '/backup_recovery',
    component: BackupRecovery,
  },
  {
    component: ApiPage,
    path: '/api_page',
  },
  {
    component: UserEdit,
    path: '/user_edit',
  },
  {
    path: '/monitor',
    component: MonitorList,
  },
  {
    path: '/task_list',
    component: TaskList,
  },
  {
    path: '/task_group',
    component: TaskGroup,
  },
  {
    path: '/task_info/:id',
    component: TaskInfo,
  },
  {
    path: '/form_page',
    component: FormPage,
  },
  {
    path: '/bug_store',
    component: BugStore,
  },
  {
    path: '/keyword',
    component: Keyword,
  },
  {
    path: '/custom_module',
    component: CustomModule,
  },
  {
    path: '/change_set',
    component: ChangeSet,
  },
  {
    path: '/change_detail',
    component: ChangeDetail,
  },
  {
    path: '/dashboard',
    component: Dashboard,
  },
  {
    path: '/vul_detail',
    component: VulDetail,
  },
  {
    path: '/securityInfo',
    component: SecurityInfo,
  },
  {
    path: '/user_manage',
    component: UserManage,
  },
  {
    path: '/message',
    component: Message,
  },
  {
    path: '/auth_method',
    component: AuthMethod,
  },
  {
    path: '/remote_help',
    component: RemoteHelp,
  },
  {
    path: '/product_info',
    component: ProductInfo,
  },
  {
    path: '/system_update',
    component: SysUpdate,
  },
  {
    path: '/log_center',
    component: LogCenter,
  },
  {
    path: '/outlink/Detail',
    component: Detail,
  },
  {
    path: '/alert_Page',
    component: AlertPage,
  },
  {
    path: '/dns_config',
    component: DnsConfig,
  },
  {
    path: '/ssh_config',
    component: SshConfig,
  },
  {
    path: '/network_config',
    component: NetworkConfig,
  },
  {
    path: '/snmp_config',
    component: SnmpConfig,
  },
  {
    path: '/router_config',
    component: RouterConfig,
  },
  {
    path: '/https_config',
    component: HttpsConfig,
  },
  {
    path: '/business_load',
    component: BusinessLoad,
  },
  {
    path: '/interface_flow',
    component: InterfaceFlow,
  },
  {
    path: '/system_control',
    component: SystemControl,
  },
  {
    path: '/system_load',
    component: SystemLoad,
  },
  {
    path: '/system_time',
    component: SysTime,
  },
  {
    path: '/error_log',
    component: ErrorLog,
  },
  {
    path: '/role_manage',
    component: Role,
  },
];
const NavDataActive = [
  {
    path: '/down',
    component: Down,
  },
  {
    path: '/form_page',
    component: FormPage,
  },
  {
    path: '/dashboard',
    component: Dashboard,
  },
  {
    path: '/task_info/:id',
    component: TaskInfo,
  },
  {
    component: ApiPage,
    path: '/api_page',
  },
  {
    path: '/message',
    component: Message,
  },
  {
    component: UserEdit,
    path: '/user_edit',
  },
  {
    path: '/user_manage',
    component: UserManage,
  },
  {
    component: AuthMethod,
    path: '/auth_method',
  },
  {
    path: '/monitor',
    component: MonitorList,
  },
  {
    path: '/task_list',
    component: TaskList,
  },
  {
    component: TaskGroup,
    path: '/task_group',
  },

  {
    component: AlertPage,
    path: '/alert_Page',
  },
  {
    component: BugStore,
    path: '/bug_store',
  },
  {
    component: ProductInfo,
    path: '/product_info',
  },
  {
    path: '/securityInfo',
    component: SecurityInfo,
  },
  {
    path: '/vul_detail',
    component: VulDetail,
  },
  {
    path: '/outlink/Detail',
    component: Detail,
  },
  {
    path: '/change_detail',
    component: ChangeDetail,
  },
];
const NavDataAudit = [
  {
    component: UserEdit,
    path: '/user_edit',
  },
  {
    component: UserManage,
    path: '/user_manage',
  },
  {
    component: ApiPage,
    path: '/api_page',
  },
  {
    component: AuthMethod,
    path: '/auth_method',
  },
  {
    component: LogCenter,
    path: '/log_center',
  },
  {
    component: BugStore,
    path: '/bug_store',
  },
  {
    component: ProductInfo,
    path: '/product_info',
  },
];

const allRouters = [
  {
    path: '/down',
    component: Down,
  },
  {
    path: '/backup_recovery',
    component: BackupRecovery,
  },
  {
    path: '/monitor',
    component: MonitorList,
  },
  {
    path: '/task_list',
    component: TaskList,
  },
  {
    path: '/task_group',
    component: TaskGroup,
  },
  {
    path: '/task_info/:id',
    component: TaskInfo,
  },
  {
    path: '/form_page',
    component: FormPage,
  },
  {
    path: '/bug_store',
    component: BugStore,
  },
  {
    path: '/keyword',
    component: Keyword,
  },
  {
    path: '/custom_module',
    component: CustomModule,
  },
  {
    path: '/change_set',
    component: ChangeSet,
  },
  {
    path: '/change_detail',
    component: ChangeDetail,
  },
  {
    path: '/dashboard',
    component: Dashboard,
  },
  {
    path: '/vul_detail',
    component: VulDetail,
  },
  {
    path: '/securityInfo',
    component: SecurityInfo,
  },
  {
    path: '/message',
    component: Message,
  },

  {
    path: '/remote_help',
    component: RemoteHelp,
  },

  {
    path: '/system_update',
    component: SysUpdate,
  },
  {
    path: '/log_center',
    component: LogCenter,
  },
  {
    path: '/outlink/Detail',
    component: Detail,
  },
  {
    path: '/alert_Page',
    component: AlertPage,
  },
  {
    path: '/dns_config',
    component: DnsConfig,
  },
  {
    path: '/ssh_config',
    component: SshConfig,
  },
  {
    path: '/network_config',
    component: NetworkConfig,
  },
  {
    path: '/snmp_config',
    component: SnmpConfig,
  },
  {
    path: '/router_config',
    component: RouterConfig,
  },
  {
    path: '/https_config',
    component: HttpsConfig,
  },
  {
    path: '/business_load',
    component: BusinessLoad,
  },
  {
    path: '/interface_flow',
    component: InterfaceFlow,
  },
  {
    path: '/system_control',
    component: SystemControl,
  },
  {
    path: '/system_load',
    component: SystemLoad,
  },
  {
    path: '/system_time',
    component: SysTime,
  },
  {
    path: '/error_log',
    component: ErrorLog,
  },
  {
    path: '/role_manage',
    component: Role,
  },
  {
    component: UserEdit,
    path: '/user_edit',
  },
  {
    component: UserManage,
    path: '/user_manage',
  },
  {
    component: ApiPage,
    path: '/api_page',
  },
  {
    component: AuthMethod,
    path: '/auth_method',
  },
  {
    component: ProductInfo,
    path: '/product_info',
  },
];

export default function Router() {
  const history = useHistory();
  const [navData, setNavData] = React.useState([]);
  const group = localStorage.getItem('group');
  let redirected = Boolean(localStorage.getItem('redirected')) || false;
  let dynamicPath = '';
  React.useEffect(async () => {
    if (group === '管理员') {
      setNavData(NavDataAdmin);
    } else if (group === '操作员') {
      setNavData(NavDataActive);
    } else if (group === '审计员') {
      setNavData(NavDataAudit);
    } else {
      setNavData(allRouters);
      await getUserInfoDetail();
      await setPermissionList();
    }
    if (!redirected && group) {
      // 根据localStorage中的group值进行重定向
      switch (group) {
        case '审计员':
          history.push('/log_center');
          break;
        case '操作员':
          history.push('/monitor');
          break;
        case '管理员':
          history.push('/keyword');
          break;
        default:
          // 默认情况可以重定向到主页或其他页面
          history.push(dynamicPath);
      }
      localStorage.setItem('redirected', true);
    }
  }, []);
  let currentUserId = '';

  const getUserInfoDetail = async () => {
    console.log(1);
    try {
      const { data } = await getUserInfoDetailApi();
      console.log(data.user_group_id);
      currentUserId = data.user_group_id;
    } catch (err) {
      console.log(err);
    }
  };
  const roleListParams = {
    page: 1,
    pageSize: 30,
    userGroupId: '',
  };
  const findFirstLink = (node) => {
    if (node.link) {
      dynamicPath = node.link;
      console.log(dynamicPath);
      return;
    }
    if (node.children && Array.isArray(node.children)) {
      for (let child of node.children) {
        findFirstLink(child);
      }
    }
  };

  const [permissions, setPermissions] = useState([]);
  const setPermissionList = async () => {
    try {
      roleListParams.userGroupId = currentUserId;
      console.log(roleListParams);
      const { data } = await getRoleListApi(roleListParams);
      const resNavs = data.data[0].modules;
      const currentNavs = [];
      allNavs.forEach((item) => {
        const matchNav = resNavs.find((subItem) => subItem.module_name === item.title);
        if (matchNav) {
          currentNavs.push(item);
        }
      });
      setPermissions(currentNavs);
      findFirstLink(currentNavs[0]);
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <Switch>
      <AuthRoute navDate={permissions}>
        {navData.map((e, i) => {
          return <Route key={i} exact path={e.path} component={e.component} />;
        })}
      </AuthRoute>
      {/*
      * 留存作备份比对
      <Route exact path="/monitor" component={MonitorList} />
      <Route exact path="/test" component={TestPage} />
      <Route exact path="/task_list" component={TaskList} />
      <Route exact path="/task_group" component={TaskGroup} />
      <Route exact path="/task_info/:id" component={TaskInfo} />
      <Route exact path="/form_page" component={FormPage} />
      <Route exact path="/bug_store" component={BugStore} />
      <Route exact path="/keyword" component={Keyword} />
      <Route exact path="/custom_module" component={CustomModule} />
      <Route exact path="/dashboard" component={Dashboard} />
      <Route exact path="/vul_detail" component={VulDetail} />
      <Route exact path="/securityInfo" component={SecurityInfo} />
      <Route exact path="/user_manage" component={UserManage} />
      <Route exact path="/message" component={Message} />
      <Route exact path="/auth_method" component={AuthMethod} />
      <Route exact path="/remote_help" component={RemoteHelp} />
      <Route exact path="/product_info" component={ProductInfo} />
      <Route exact path="/system_update" component={SysUpdate} />
      <Route exact path="/backup_recovery" component={BackupRecovery} />
      <Route exact path="/log_center" component={LogCenter} />
      <Route exact path="/outlink/Detail" component={Detail} />
      <Route exact path="/alert_Page" component={AlertPage} />
      <Route exact path="/dns_config" component={DnsConfig} />
      <Route exact path="/ssh_config" component={SshConfig} />
      <Route exact path="/network_config" component={NetworkConfig} />
      <Route exact path="/snmp_config" component={SnmpConfig} />
      <Route exact path="/router_config" component={RouterConfig} />
      <Route exact path="/https_config" component={HttpsConfig} />
      <Route exact path="/business_load" component={BusinessLoad} />
      <Route exact path="/interface_flow" component={InterfaceFlow} />
      <Route exact path="/system_control" component={SystemControl} />
      <Route exact path="/system_load" component={SystemLoad} />
      <Route exact path="/system_time" component={SysTime} />
      <Route exact path="/error_log" component={ErrorLog} />
      <Route exact path="/user_edit" component={UserEdit} />
      */}

      {/* <Route path="/**" exact render={(e) => {
        console.log('[  ]-355', e)
        return <Redirect to="/" />}} /> */}
    </Switch>
  );
}
